<template>
  <div class="dashboard-container">
    <el-card shadow="never">
      <div class="map-container">
        <div ref="mapContainer" class="map" />
        <div class="controls">
          <button @click="addland">添加地块</button>
        </div>
      </div>
    </el-card>
  </div>

  <div class="dashboard-container">
    <div class="button-container">
      <div v-for="(button, index) in buttons" :key="index" class="button-group">
        <el-button
          type="primary"
          class="main-button"
          :style="{ background: button.color }"
          @click="openDialog(index)"
        >
          <img :src="button.iconPath" alt="iconfont" class="button-icon" />
          {{ button.label }}
        </el-button>
      </div>
    </div>

    <!-- 弹窗模态框 -->
    <el-dialog v-model="dialogVisible" width="30%" :title="selectedButton.label">
      <div class="sub-buttons-dialog">
        <el-button
          v-for="(subButton, subIndex) in selectedButton.subButtons"
          :key="subIndex"
          type="success"
          class="dialog-sub-button"
          @click="handleSubButtonClick(subButton.route)"
        >
          <img :src="subButton.iconPath" alt="icon" class="button-icon" />
          {{ subButton.label }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from "vue";
import { useUserStore } from "@/store/modules/user";
import StatsAPI, { VisitStatsVO } from "@/api/system/log";
import NoticeAPI, { NoticePageVO } from "@/api/system/notice";
import WebSocketManager from "@/utils/websocket";
import router from "@/router";
import html2canvas from "html2canvas";
import { log } from "console";

const addland = () => {
  router.push({ path: "/addland" });
};

// 高德地图API的key，需要替换为你自己申请的有效key
const apiKey = "c82372a2fbfc00f4b34488c43b2c5e0c";

const noticeDetailRef = ref();
const mapContainer = ref<HTMLElement | null>(null);
let map: AMap.Map;
let mouseTool: AMap.MouseTool;
let currentPolygon: AMap.Polygon | null = null; // 存储当前绘制的多边形
const isDrawing = ref(false); // 是否正在绘制状态

// 初始化地图及相关绘制工具
const initMap = async () => {
  await nextTick(); // 确保 DOM 更新后再初始化地图
  map = new AMap.Map(mapContainer.value!, {
    center: [105.38192, 29.15041],
    layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
    zoom: 13,
  });
  // 合并 onMounted 钩子
  onMounted(() => {
    // 加载高德地图脚本
    const script = document.createElement("script");
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${apiKey}&plugin=AMap.MouseTool`;
    script.onload = () => {
      initMap();
      loadSavedPolygon(); // 初始化时加载保存的多边形

      // 加载保存的地图图片（如果有）
      const savedMapImage = localStorage.getItem("savedMapImage");
      if (savedMapImage) {
        const img = new Image();
        img.src = savedMapImage;
        img.onload = () => {
          mapContainer.value?.appendChild(img);
        };
      }
    };
    document.body.appendChild(script);

    loadVisitStatsData();

    NoticeAPI.getMyNoticePage({ pageNum: 1, pageSize: 10 }).then((data) => {
      notices.value = data.list;
    });

    WebSocketManager.subscribeToTopic("/topic/onlineUserCount", (data) => {
      console.log("收到在线用户数量：", data);
      onlineUserCount.value = JSON.parse(data);
    });
  });

  // 在 mouseTool.on("draw", ...) 中调用 saveMapAfterCompleteDrawing
  mouseTool.on("draw", (event: any) => {
    currentPolygon = event.obj; // 保存绘制的多边形对象
    isDrawing.value = false; // 结束绘制状态
    console.log("多边形绘制完成:", currentPolygon.getPath());
    saveMapAfterCompleteDrawing(); // 保存地图图片
  });

  // 确保每个子按钮都有有效的图标路径
  const buttons = ref([
    {
      label: "组织机构",
      color: "#48B16A",
      iconPath: "/iconfont/Vector.png",
      subButtons: [
        {
          label: "职责分工",
          route: "/dashboard/duty",
          iconPath: "/iconfont/people.svg",
          color: "#48B16A",
        },
        { label: "设施设备", route: "/dashboard/equipment", iconPath: "/iconfont/drone.svg" },
        { label: "安全生产", route: "/dashboard/safety", iconPath: "/iconfont/safety.svg" },
        {
          label: "卫生管理",
          route: "/dashboard/hygiene",
          iconPath: "/iconfont/hygiene.svg",
          color: "#48B16A",
        },
      ],
    },
    // 其他按钮...
  ]);

  // 动态获取当前时间
  const greetings = computed(() => {
    const hours = new Date().getHours();
    if (hours >= 6 && hours < 8) {
      return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
    } else if (hours >= 8 && hours < 12) {
      return "上午好，" + userStore.userInfo.nickname + "！";
    } else if (hours >= 12 && hours < 18) {
      return "下午好，" + userStore.userInfo.nickname + "！";
    } else if (hours >= 18 && hours < 24) {
      return "晚上好，" + userStore.userInfo.nickname + "！";
    } else {
      return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
    }
  });
  mouseTool = new AMap.MouseTool(map);

  // 监听绘制完成事件
  mouseTool.on("draw", (event: any) => {
    currentPolygon = event.obj; // 保存绘制的多边形对象
    isDrawing.value = false; // 结束绘制状态
    console.log("多边形绘制完成:", currentPolygon.getPath());
  });

  // 监听右键点击事件，结束绘制
  map.on("rightclick", () => {
    if (isDrawing.value) {
      mouseTool.close(); // 结束当前绘制
      isDrawing.value = false;
    }
  });
};

// 开始绘制多边形
const startDrawing = () => {
  if (currentPolygon) {
    map.remove(currentPolygon); // 清除之前的多边形
    currentPolygon = null;
  }
  mouseTool.polygon({
    strokeColor: "#FFA43D",
    strokeOpacity: 1,
    strokeWeight: 6,
    fillColor: "rgba(254, 168, 71, 0.37)",
    fillOpacity: 0.4,
    strokeStyle: "solid",
  });
  isDrawing.value = true;
};

// 完成绘制（停止工具，但保留多边形）
const completeDrawing = () => {
  mouseTool.close(); // 停止绘制工具
  isDrawing.value = false;
  // 完成绘制后保存地图为图片
};

// 完成绘制后保存地图为图片的具体实现
const saveMapAfterCompleteDrawing = async () => {
  if (mapContainer.value && currentPolygon) {
    try {
      const canvas = await html2canvas(mapContainer.value);
      const imageData = canvas.toDataURL("image/png");
      localStorage.setItem("savedMapImage", imageData);
      alert("地图图片已成功保存到本地存储！");
    } catch (error) {
      console.error("保存地图图片时发生错误:", error);
    }
  }
};

// 取消绘制（清除当前多边形）
const cancelDrawing = () => {
  mouseTool.close(true); // 停止绘制并清除未完成图形
  if (currentPolygon) {
    map.remove(currentPolygon); // 移除地图上的多边形
    currentPolygon = null;
  }
  isDrawing.value = false;
};

// 保存多边形到 localStorage
const savePolygon = () => {
  if (currentPolygon) {
    const polygonPath = currentPolygon.getPath().map((point: AMap.LngLat) => ({
      lng: point.lng,
      lat: point.lat,
    }));
    localStorage.setItem("savedPolygon", JSON.stringify(polygonPath));
    alert("多边形已保存！");
  }
};

// 删除多边形
const deletePolygon = () => {
  if (currentPolygon) {
    map.remove(currentPolygon);
    currentPolygon = null;
    localStorage.removeItem("savedPolygon");
    alert("多边形已删除！");
  }
};

// 保存地图为图片到本地存储（localStorage）
const saveMapAsImage = async () => {
  if (mapContainer.value) {
    try {
      const canvas = await html2canvas(mapContainer.value);
      const imageData = canvas.toDataURL("image/png");
      localStorage.setItem("savedMapImage", imageData);
      alert("地图图片已成功保存到本地存储！");
    } catch (error) {
      console.error("保存地图图片时发生错误:", error);
    }
  }
};

// 加载保存的多边形（如果有）
const loadSavedPolygon = () => {
  const savedPolygon = localStorage.getItem("savedPolygon");
  if (savedPolygon) {
    try {
      const polygonPath = JSON.parse(savedPolygon);
      if (Array.isArray(polygonPath) && polygonPath.every((point) => point.lng && point.lat)) {
        const path = polygonPath.map(
          (point: { lng: number; lat: number }) => new AMap.LngLat(point.lng, point.lat)
        );
        currentPolygon = new AMap.Polygon({
          path,
          strokeColor: "#FFA43D",
          strokeOpacity: 1,
          strokeWeight: 6,
          fillColor: "rgba(254, 168, 71, 0.37)",
          fillOpacity: 0.4,
        });
        map.add(currentPolygon); // 在地图上加载保存的多边形
      }
    } catch (error) {
      console.error("加载保存的多边形时发生错误:", error);
    }
  }
};

onMounted(() => {
  // 加载高德地图脚本
  const script = document.createElement("script");
  script.src = `https://webapi.amap.com/maps?v=2.0&key=${apiKey}&plugin=AMap.MouseTool`;
  script.onload = () => {
    initMap();
    loadSavedPolygon(); // 初始化时加载保存的多边形

    // 加载保存的地图图片（如果有）
    const savedMapImage = localStorage.getItem("savedMapImage");
    if (savedMapImage) {
      const img = new Image();
      img.src = savedMapImage;
      img.onload = () => {
        mapContainer.value?.appendChild(img);
      };
    }
  };
  document.body.appendChild(script);
});

const userStore = useUserStore();
const date: Date = new Date();
const greetings = computed(() => {
  const hours = date.getHours();
  if (hours >= 6 && hours < 8) {
    return "晨起披衣出草堂，轩窗已自喜微凉🌅！";
  } else if (hours >= 8 && hours < 12) {
    return "上午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 12 && hours < 18) {
    return "下午好，" + userStore.userInfo.nickname + "！";
  } else if (hours >= 18 && hours < 24) {
    return "晚上好，" + userStore.userInfo.nickname + "！";
  } else {
    return "偷偷向银河要了一把碎星，只等你闭上眼睛撒入你的梦中，晚安🌛！";
  }
});

const dialogVisible = ref(false);
const selectedButton = ref({ label: "", subButtons: [] });
const openDialog = (index: string | number) => {
  selectedButton.value = buttons.value[index];
  dialogVisible.value = true;
};

const onlineUserCount = ref(0);

const visitStatsLoading = ref(true);
const visitStatsList = ref<VisitStats[]>([]);

interface VisitStats {
  title: string;
  icon: string;
  tagType: "primary" | "success" | "warning";
  growthRate: number;
  granularity: string;
  todayCount: number;
  totalCount: number;
}

const loadVisitStatsData = async () => {
  const list: VisitStatsVO[] = await StatsAPI.getVisitStats();

  if (list) {
    const tagTypes: ("primary" | "success" | "warning")[] = ["primary", "success", "warning"];
    const transformedList: VisitStats[] = list.map((item, index) => ({
      title: item.title,
      icon: getVisitStatsIcon(item.type),
      tagType: tagTypes[index % tagTypes.length],
      growthRate: item.growthRate,
      granularity: "日",
      todayCount: item.todayCount,
      totalCount: item.totalCount,
    }));
    visitStatsList.value = transformedList;
    visitStatsLoading.value = false;
  }
};

const formatGrowthRate = (growthRate: number = 0) => {
  if (growthRate === 0) {
    return "-";
  }

  const formattedRate = Math.abs(growthRate * 100)
    .toFixed(2)
    .replace(/\.?0+$/, "");
  return formattedRate + "%";
};

const getGrowthRateClass = (growthRate: number): string => {
  if (growthRate > 0) {
    return "color-[--el-color-danger]";
  } else if (growthRate < 0) {
    return "color-[--el-color-success]";
  } else {
    return "color-[--el-color-info]";
  }
};

const getVisitStatsIcon = (type: any): any => {
  switch (type) {
    case "type1":
      return "icon1";
    case "type2":
      return "icon2";
    default:
      return "defaultIcon";
  }
};

const notices = ref<NoticePageVO[]>([]);

const viewMoreNotice = () => {
  router.push({ path: "/myNotice" });
};

const viewNoticeDetail = (id: string) => {
  noticeDetailRef.value.openNotice(id);
};

interface SubButton {
  label: string;
  route: string;
  iconPath: string; // 新增图标路径
  color?: string; // 新增颜色属性
}
const buttons = ref<
  {
    label: string;
    color: string;
    iconPath: string; // 新增图标路径
    subButtons: SubButton[];
  }[]
>([
  {
    label: "组织机构",
    color: "#48B16A",
    iconPath: "/iconfont/Vector.png", // 新增图标路径
    subButtons: [
      {
        label: "职责分工",
        route: "/dashboard/duty",
        iconPath: "/iconfont/people.svg",
        color: "#48B16A",
      }, // 新增图标路径
      { label: "设施设备", route: "/dashboard/equipment", iconPath: "/iconfont/drone.svg" }, // 新增图标路径
      { label: "安全生产", route: "/dashboard/safety", iconPath: "/iconfont/safety.svg" }, // 新增图标路径
      {
        label: "卫生管理",
        route: "/dashboard/hygiene",
        iconPath: "/iconfont/hygiene.svg",
        color: "#48B16A",
      }, // 新增图标路径
    ],
  },
  {
    label: "生产地块",
    color: "#47B19E",
    iconPath: "/iconfont/field.svg",
    subButtons: [
      { label: "基地选择", route: "/Base selection", iconPath: "/iconfont/Vector.svg" },
      { label: "土壤水源", route: "/Climatic environment", iconPath: "/iconfont/soil.svg" },
      {
        label: "气候环境",
        route: "/Soil water source",
        iconPath: "/iconfont/fluent_weather-cloudy-20-filled.svg",
      },
      {
        label: "基地建设",
        route: "/Base construction",
        iconPath: "/iconfont/material-symbols_construction.svg",
      },
    ],
  },
  {
    label: "种子种苗",
    color: "#48B16A",
    iconPath: "/iconfont/seed.svg",
    subButtons: [
      {
        label: "基原鉴定",
        route: "/Primitive identification",
        iconPath: "/iconfont/token_rootstock.svg",
      },
      {
        label: "生药鉴定",
        route: "/Identification of crude drug",
        iconPath: "/iconfont/ion_leaf-sharp.svg",
      },
      { label: "繁育材料", route: "/Breeding material", iconPath: "/iconfont/soil 2.svg" },
      {
        label: "繁育方法",
        route: "/Breeding method",
        iconPath: "/iconfont/material-symbols-light_potted-plant.svg",
      },
    ],
  },
  {
    label: "定植栽培",
    color: "#47B19E",
    iconPath: "/iconfont/trowel1.svg",
    subButtons: [
      {
        label: "种苗来源",
        route: "/Seed and seedling source",
        iconPath: "/iconfont/Vector (1).svg",
      },
      { label: "土地整理", route: "/Land consolidation", iconPath: "/iconfont/field 4.svg" },
      { label: "栽培方法", route: "/Cultivation method", iconPath: "/iconfont/plant 1.svg" },
      { label: "幼苗养护", route: "/Seedling maintenance", iconPath: "/iconfont/plantation 1.svg" },
    ],
  },
  {
    label: "田间管理",
    color: "#47B19E",
    iconPath: "/iconfont/irrigate 2.png",
    subButtons: [
      { label: "浇水除草", route: "/Water and weed", iconPath: "/iconfont/Vector (2).svg" },
      {
        label: "中耕施肥",
        route: "/Ploughing and fertilizing",
        iconPath: "/iconfont/pesticide 2.svg",
      },
      {
        label: "病虫防治",
        route: "/Disease and insect control",
        iconPath: "/iconfont/pest-control 1.svg",
      },
      {
        label: "越冬保护",
        route: "/Overwintering protection",
        iconPath: "/iconfont/snowflake 2.svg",
      },
    ],
  },
  {
    label: "采收加工",
    color: "#48B16A",
    iconPath: "/iconfont/sickle 1.svg",
    subButtons: [
      { label: "质量检测", route: "/Quality inspection", iconPath: "/iconfont/Vector (3).svg" },
      { label: "采收方法", route: "/Harvesting method", iconPath: "/iconfont/scythe 1.svg" },
      { label: "晾晒加工", route: "/Drying finish", iconPath: "/iconfont/steam 2.svg" },
      {
        label: "包装入库",
        route: "/Packing and warehousing",
        iconPath: "/iconfont/Vector (4).svg",
      },
    ],
  },
  {
    label: "仓储运输",
    color: "#47B19E",
    iconPath: "/iconfont/shipment.svg",
    subButtons: [
      { label: "设施管理", route: "/Facility management", iconPath: "/iconfont/Vector (5).svg" },
      { label: "标签格式", route: "/Label format", iconPath: "/iconfont/barcode 1.svg" },
      { label: "检查制度", route: "/Inspection system", iconPath: "/iconfont/control.svg" },
      { label: "放行制度", route: "/Release system", iconPath: "/iconfont/qc 4.svg" },
    ],
  },
  {
    label: "质量保证",
    color: "#48B16A",
    iconPath: "/iconfont/quality 2.svg",
    subButtons: [
      { label: "质量标准", route: "/Quality standard", iconPath: "/iconfont/Vector (6).svg" },
      { label: "质量控制", route: "/Quality control", iconPath: "/iconfont/verification 1.svg" },
      { label: "质量保证", route: "/Quality assurance", iconPath: "/iconfont/shield 1.svg" },
      { label: "检验分析", route: "/Inspection analysis", iconPath: "/iconfont/analytics 1.svg" },
    ],
  },
]);

const showSubButtons = ref<boolean[]>(buttons.value.map(() => false));

const toggleSubButtons = (index: number) => {
  showSubButtons.value[index] = !showSubButtons.value[index];
};

const handleSubButtonClick = (route: string) => {
  console.log("点击了子按钮：", route);
  router.push({ path: route });
  dialogVisible.value = false;
};

onMounted(() => {
  loadVisitStatsData();

  NoticeAPI.getMyNoticePage({ pageNum: 1, pageSize: 10 }).then((data) => {
    notices.value = data.list;
  });

  WebSocketManager.subscribeToTopic("/topic/onlineUserCount", (data) => {
    console.log("收到在线用户数量：", data);
    onlineUserCount.value = JSON.parse(data);
  });
});
</script>

<style lang="scss" scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map {
  width: 100%;
  height: 500px;
}

.controls {
  position: absolute;
  top: 10px;
  left: 10px;
  display: flex;
  gap: 10px;
}

button {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 5px;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:enabled {
  background-color: #38a871;
}

.sub-buttons-dialog {
  display: grid;
  grid-template-columns: repeat(2, minmax(150px, 1fr)); /* 自适应列布局 */
  gap: 20px;
  text-align: center;
  padding: 20px; /* 增加 padding 以扩大背景区域 */
  background-color: white; /* 设置白色背景 */
  border-radius: 8px; /* 可选：添加圆角效果 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 可选：添加阴影效果 */

  .dialog-sub-button {
    width: 100%; /* 确保按钮占据整个列的宽度 */
    height: 100px;
    margin-left: 0px;
    font-size: 16px;
    font-weight: bold;
    display: flex; /* 使用 Flexbox 布局 */
    align-items: center; /* 垂直居中对齐 */
    justify-content: center; /* 水平居中对齐 */
    background-color: #47b19e; /* 子按钮的背景颜色 */
    border: 1px solid #ccc; /* 子按钮的边框 */
    border-radius: 4px; /* 子按钮的圆角 */
    transition: background-color 0.3s; /* 添加过渡效果 */

    &:hover {
      background-color: #127dc5; /* 鼠标悬停时的背景颜色 */
    }
  }
}

.button-icon {
  width: 30px; /* 图标的宽度 */
  height: 30px; /* 图标的高度 */
  margin-right: 8px; /* 图标与文字之间的间距 */
}

.sub-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60px;
}

.sub-button {
  width: 100%;
  height: 80px;
}
.map-iframe {
  width: 100%;
  height: 400px;
  text-align: center;
}

.map-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;

  #container {
    width: 100%;
    height: 450px;
  }
}

.dashboard-container {
  position: relative;
  padding: 0px;

  .button-container {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(2, auto);

    .button-group {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .main-button {
      width: 250px;
      height: 118px;
      margin-bottom: 10px;
      color: white;
      border: none;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .sub-buttons {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .sub-button {
      width: 200px;
      height: 50px;
    }
  }
}
</style>
